<template>
  <div class="settings-view">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="title-section">
          <h2>
            <el-icon><Setting /></el-icon>
            {{ $t('workReports.layout.tabs.settings') }}
          </h2>
          <p>{{ $t('workReports.settings.subtitle') }}</p>
        </div>
        <div class="action-section">
          <el-button type="primary" @click="handleSaveAll" :loading="saving">
            <el-icon><Check /></el-icon>
            {{ $t('workReports.settings.saveAll') }}
          </el-button>
          <el-button @click="handleResetAll">
            <el-icon><RefreshLeft /></el-icon>
            {{ $t('workReports.settings.resetDefault') }}
          </el-button>
        </div>
      </div>
    </div>

    <!-- 设置内容 -->
    <div class="settings-content">
      <!-- AI报告生成设置 -->
      <el-card class="setting-card">
        <template #header>
          <div class="card-header">
            <h3>
              <el-icon><ChatDotRound /></el-icon>
              {{ $t('workReports.settings.aiGeneration.title') }}
            </h3>
            <el-switch v-model="aiSettings.enabled" @change="handleAISettingChange" />
          </div>
        </template>

        <el-form :model="aiSettings" label-width="120px" :disabled="!aiSettings.enabled">
          <el-form-item :label="$t('workReports.settings.aiGeneration.model')">
            <div class="ai-model-info">
              <el-tag type="info" size="large">{{ currentModelLabel }}</el-tag>
              <div class="form-tip">
                {{ $t('workReports.settings.aiGeneration.modelTip') }}
                <el-button type="primary" link @click="goToGlobalSettings">{{ $t('workReports.settings.aiGeneration.globalSettings') }}</el-button>
              </div>
            </div>
          </el-form-item>

          <el-form-item :label="$t('workReports.settings.aiGeneration.temperature')">
            <el-slider
              v-model="aiSettings.temperature"
              :min="0"
              :max="1"
              :step="0.1"
              show-input
              style="width: 300px"
            />
            <div class="form-tip">{{ $t('workReports.settings.aiGeneration.temperatureTip') }}</div>
          </el-form-item>

          <el-form-item :label="$t('workReports.settings.aiGeneration.maxLength')">
            <el-input-number
              v-model="aiSettings.maxLength"
              :min="100"
              :max="4000"
              :step="100"
              style="width: 200px"
            />
            <div class="form-tip">{{ $t('workReports.settings.aiGeneration.maxLengthTip') }}</div>
          </el-form-item>

          <el-form-item :label="$t('workReports.settings.reportSettings.style')">
            <el-radio-group v-model="aiSettings.style">
              <el-radio value="professional">{{ $t('workReports.settings.reportSettings.styles.professional') }}</el-radio>
              <el-radio value="casual">{{ $t('workReports.settings.reportSettings.styles.casual') }}</el-radio>
              <el-radio value="detailed">{{ $t('workReports.settings.reportSettings.styles.detailed') }}</el-radio>
              <el-radio value="concise">{{ $t('workReports.settings.reportSettings.styles.concise') }}</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item :label="$t('workReports.settings.reportSettings.includeContent')">
            <el-checkbox-group v-model="aiSettings.includeContent">
              <el-checkbox label="summary">{{ $t('workReports.settings.reportSettings.contents.summary') }}</el-checkbox>
              <el-checkbox label="achievements">{{ $t('workReports.settings.reportSettings.contents.achievements') }}</el-checkbox>
              <el-checkbox label="challenges">{{ $t('workReports.settings.reportSettings.contents.challenges') }}</el-checkbox>
              <el-checkbox label="nextSteps">{{ $t('workReports.settings.reportSettings.contents.plans') }}</el-checkbox>
              <el-checkbox label="suggestions">{{ $t('workReports.settings.reportSettings.contents.suggestions') }}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 报告模板设置 -->
      <el-card class="setting-card">
        <template #header>
          <div class="card-header">
            <h3>
              <el-icon><Document /></el-icon>
              {{ $t('workReports.settings.templateSettings.title') }}
            </h3>
            <el-button size="small" @click="showTemplateDialog = true">
              <el-icon><Plus /></el-icon>
              {{ $t('workReports.settings.templateSettings.newTemplate') }}
            </el-button>
          </div>
        </template>

        <div class="template-list">
          <div
            v-for="template in reportTemplates"
            :key="template.id"
            class="template-item"
            :class="{ active: template.id === templateSettings.defaultTemplate }"
            @click="selectTemplate(template.id)"
          >
            <div class="template-info">
              <h4>{{ template.name }}</h4>
              <p>{{ template.description }}</p>
              <div class="template-meta">
                <el-tag size="small">{{ template.type }}</el-tag>
                <span class="template-date">{{ formatDate(template.updatedAt) }}</span>
              </div>
            </div>
            <div class="template-actions">
              <el-button size="small" @click.stop="editTemplate(template)">
                <el-icon><Edit /></el-icon>
              </el-button>
              <el-button size="small" @click.stop="previewTemplate(template)">
                <el-icon><View /></el-icon>
              </el-button>
              <el-button
                size="small"
                type="danger"
                @click.stop="deleteTemplate(template.id)"
                :disabled="template.isSystem"
              >
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 模板编辑对话框 -->
    <el-dialog
      v-model="showTemplateDialog"
      :title="editingTemplate ? $t('workReports.settings.templateDialog.editTemplate') : $t('workReports.settings.templateDialog.newTemplate')"
      width="60%"
      :before-close="handleCloseTemplateDialog"
    >
      <el-form :model="templateForm" label-width="80px" ref="templateFormRef">
        <el-form-item :label="$t('workReports.settings.templateDialog.templateName')" required>
          <el-input v-model="templateForm.name" :placeholder="$t('workReports.settings.templateDialog.templateNamePlaceholder')" />
        </el-form-item>

        <el-form-item :label="$t('workReports.settings.templateDialog.templateType')">
          <el-select v-model="templateForm.type" :placeholder="$t('workReports.settings.templateDialog.selectTemplateType')">
            <el-option :label="$t('workReports.settings.templateDialog.templateTypes.daily')" value="DAILY" />
            <el-option :label="$t('workReports.settings.templateDialog.templateTypes.weekly')" value="WEEKLY" />
            <el-option :label="$t('workReports.settings.templateDialog.templateTypes.monthly')" value="MONTHLY" />
          </el-select>
        </el-form-item>

        <el-form-item :label="$t('workReports.settings.templateDialog.templateDescription')">
          <el-input
            v-model="templateForm.description"
            type="textarea"
            :rows="3"
            :placeholder="$t('workReports.settings.templateDialog.templateDescriptionPlaceholder')"
          />
        </el-form-item>

        <el-form-item :label="$t('workReports.settings.templateDialog.templateContent')">
          <el-input
            v-model="templateForm.content"
            type="textarea"
            :rows="15"
            :placeholder="$t('workReports.settings.templateDialog.templateContentPlaceholder')"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="showTemplateDialog = false">{{ $t('common.actions.cancel') }}</el-button>
        <el-button type="primary" @click="handleSaveTemplate" :loading="savingTemplate">
          {{ $t('common.actions.save') }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useAIChatStore } from '@/stores/aiChatStore'
import {
  Setting, ChatDotRound, Check, RefreshLeft, Document, Plus, Edit, View, Delete
} from '@element-plus/icons-vue'

const router = useRouter()
const aiChatStore = useAIChatStore()

// ==================== 响应式数据 ====================


const saving = ref(false)
const showTemplateDialog = ref(false)
const editingTemplate = ref<any>(null)
const savingTemplate = ref(false)

// AI设置
const aiSettings = reactive({
  enabled: true,
  temperature: 0.7,
  maxLength: 2000,
  style: 'professional',
  includeContent: ['summary', 'achievements', 'nextSteps']
})

// 计算属性：当前AI模型标签
const currentModelLabel = computed(() => {
  const currentModel = aiChatStore.currentModel
  const modelMap: Record<string, string> = {
    'THUDM/GLM-4.1V-9B-Thinking': 'GLM-4.1V-9B-Thinking',
    'THUDM/GLM-Z1-9B-0414': 'GLM-Z1-9B-0414',
    'Qwen/Qwen3-8B': 'Qwen3-8B',
    'deepseek-ai/DeepSeek-R1-0528-Qwen3-8B': 'DeepSeek-R1'
  }
  return modelMap[currentModel] || currentModel
})

// 模板设置
const templateSettings = reactive({
  defaultTemplate: 'default-daily'
})

// 报告模板列表
const reportTemplates = ref([
  {
    id: 'default-daily',
    name: '默认日报模板',
    type: 'DAILY',
    description: '标准的工作日报模板，包含工作总结和计划',
    content: '# {{date}} 工作日报\n\n## 今日工作总结\n{{workRecords}}\n\n## 主要成果\n{{achievements}}\n\n## 明日计划\n{{nextSteps}}',
    isSystem: true,
    updatedAt: '2025-01-10'
  },
  {
    id: 'default-weekly',
    name: '默认周报模板',
    type: 'WEEKLY',
    description: '标准的工作周报模板，包含周度总结和分析',
    content: '# {{dateRange}} 工作周报\n\n## 本周工作总结\n{{workRecords}}\n\n## 重要成果\n{{achievements}}\n\n## 遇到的挑战\n{{challenges}}\n\n## 下周计划\n{{nextSteps}}',
    isSystem: true,
    updatedAt: '2025-01-10'
  },
  {
    id: 'default-monthly',
    name: '默认月报模板',
    type: 'MONTHLY',
    description: '标准的工作月报模板，包含月度总结和规划',
    content: '# {{month}} 工作月报\n\n## 本月工作总结\n{{workRecords}}\n\n## 重要成果\n{{achievements}}\n\n## 数据分析\n{{statistics}}\n\n## 下月规划\n{{nextSteps}}',
    isSystem: true,
    updatedAt: '2025-01-10'
  }
])



// 模板表单
const templateForm = reactive({
  name: '',
  type: 'DAILY',
  description: '',
  content: ''
})

// ==================== 方法 ====================

/**
 * 初始化页面
 */
const initPage = () => {
  loadSettings()
}

/**
 * 加载设置
 */
const loadSettings = () => {
  // 从localStorage或API加载设置
  const savedSettings = localStorage.getItem('workReportSettings')
  if (savedSettings) {
    try {
      const settings = JSON.parse(savedSettings)
      Object.assign(aiSettings, settings.aiSettings || {})
      Object.assign(templateSettings, settings.templateSettings || {})
    } catch (error) {
      console.error('加载设置失败:', error)
    }
  }
}

/**
 * 保存所有设置
 */
const handleSaveAll = async () => {
  try {
    saving.value = true

    const allSettings = {
      aiSettings: { ...aiSettings },
      templateSettings: { ...templateSettings }
    }

    // 保存到localStorage（实际项目中应该保存到服务器）
    localStorage.setItem('workReportSettings', JSON.stringify(allSettings))

    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))

    ElMessage.success('设置保存成功')
  } catch (error) {
    console.error('保存设置失败:', error)
    ElMessage.error('保存设置失败')
  } finally {
    saving.value = false
  }
}

/**
 * 重置所有设置
 */
const handleResetAll = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要重置所有设置为默认值吗？此操作不可恢复。',
      '确认重置',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    // 重置为默认值
    Object.assign(aiSettings, {
      enabled: true,
      temperature: 0.7,
      maxLength: 2000,
      style: 'professional',
      includeContent: ['summary', 'achievements', 'nextSteps']
    })

    Object.assign(templateSettings, {
      defaultTemplate: 'default-daily'
    })

    // 清除localStorage
    localStorage.removeItem('workReportSettings')

    ElMessage.success('设置已重置为默认值')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('重置设置失败:', error)
    }
  }
}

/**
 * AI设置变化处理
 */
const handleAISettingChange = () => {
  // 自动保存AI设置
  const settings = JSON.parse(localStorage.getItem('workReportSettings') || '{}')
  settings.aiSettings = { ...aiSettings }
  localStorage.setItem('workReportSettings', JSON.stringify(settings))
}

/**
 * 选择模板
 */
const selectTemplate = (templateId: string) => {
  templateSettings.defaultTemplate = templateId
  ElMessage.success('默认模板已更新')
}

/**
 * 编辑模板
 */
const editTemplate = (template: any) => {
  editingTemplate.value = template
  Object.assign(templateForm, {
    name: template.name,
    type: template.type,
    description: template.description,
    content: template.content
  })
  showTemplateDialog.value = true
}

/**
 * 预览模板
 */
const previewTemplate = (template: any) => {
  ElMessageBox.alert(template.content, `模板预览 - ${template.name}`, {
    confirmButtonText: '关闭',
    customClass: 'template-preview-dialog'
  })
}

/**
 * 删除模板
 */
const deleteTemplate = async (templateId: string) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这个模板吗？此操作不可恢复。',
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const index = reportTemplates.value.findIndex(t => t.id === templateId)
    if (index !== -1) {
      reportTemplates.value.splice(index, 1)
      ElMessage.success('模板删除成功')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除模板失败:', error)
    }
  }
}

/**
 * 保存模板
 */
const handleSaveTemplate = async () => {
  if (!templateForm.name.trim()) {
    ElMessage.error('请输入模板名称')
    return
  }

  if (!templateForm.content.trim()) {
    ElMessage.error('请输入模板内容')
    return
  }

  try {
    savingTemplate.value = true

    if (editingTemplate.value) {
      // 编辑现有模板
      const index = reportTemplates.value.findIndex(t => t.id === editingTemplate.value.id)
      if (index !== -1) {
        Object.assign(reportTemplates.value[index], {
          name: templateForm.name,
          type: templateForm.type,
          description: templateForm.description,
          content: templateForm.content,
          updatedAt: new Date().toISOString().split('T')[0]
        })
      }
      ElMessage.success('模板更新成功')
    } else {
      // 创建新模板
      const newTemplate = {
        id: `custom-${Date.now()}`,
        name: templateForm.name,
        type: templateForm.type,
        description: templateForm.description,
        content: templateForm.content,
        isSystem: false,
        updatedAt: new Date().toISOString().split('T')[0]
      }
      reportTemplates.value.push(newTemplate)
      ElMessage.success('模板创建成功')
    }

    showTemplateDialog.value = false
    resetTemplateForm()
  } catch (error) {
    console.error('保存模板失败:', error)
    ElMessage.error('保存模板失败')
  } finally {
    savingTemplate.value = false
  }
}

/**
 * 关闭模板对话框
 */
const handleCloseTemplateDialog = () => {
  showTemplateDialog.value = false
  resetTemplateForm()
}

/**
 * 重置模板表单
 */
const resetTemplateForm = () => {
  editingTemplate.value = null
  Object.assign(templateForm, {
    name: '',
    type: 'DAILY',
    description: '',
    content: ''
  })
}





// ==================== 工具方法 ====================

/**
 * 跳转到全局设置页面
 */
const goToGlobalSettings = () => {
  router.push('/dashboard/settings')
}

/**
 * 格式化日期显示
 */
const formatDate = (dateStr: string): string => {
  const date = new Date(dateStr)
  return date.toLocaleDateString('zh-CN')
}

// ==================== 生命周期 ====================

onMounted(() => {
  initPage()
})
</script>

<style scoped lang="scss">
.settings-view {
  // padding: 20px;
  background-color: var(--el-bg-color-page);
}

// 页面头部
.page-header {
  margin-bottom: 20px;

  .header-content {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;

    .title-section {
      h2 {
        margin: 0 0 8px 0;
        display: flex;
        align-items: center;
        gap: 8px;
        font-size: 24px;
        color: var(--el-text-color-primary);
        font-weight: 600;
      }

      p {
        margin: 0;
        color: var(--el-text-color-regular);
        font-size: 14px;
      }
    }

    .action-section {
      display: flex;
      gap: 12px;
    }
  }
}

// 设置内容
.settings-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

// 设置卡片
.setting-card {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    h3 {
      margin: 0;
      display: flex;
      align-items: center;
      gap: 8px;
      font-size: 16px;
      color: var(--el-text-color-primary);
      font-weight: 600;
    }
  }

  .form-tip {
    font-size: 12px;
    color: var(--el-text-color-placeholder);
    margin-top: 4px;
  }
}

// AI模型信息样式
.ai-model-info {
  display: flex;
  flex-direction: column;
  gap: 8px;

  .form-tip {
    display: flex;
    align-items: center;
    gap: 4px;
    font-size: 12px;
    color: var(--el-text-color-regular);
  }
}

// 模板列表
.template-list {
  display: flex;
  flex-direction: column;
  gap: 12px;

  .template-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px;
    border: 1px solid var(--el-border-color);
    border-radius: 8px;
    cursor: pointer;
    transition: all 0.3s ease;

    &:hover {
      border-color: var(--el-color-primary);
      background-color: var(--el-color-primary-light-9);
    }

    &.active {
      border-color: var(--el-color-primary);
      background-color: var(--el-color-primary-light-9);

      .template-info h4 {
        color: var(--el-color-primary);
      }
    }

    .template-info {
      flex: 1;

      h4 {
        margin: 0 0 4px 0;
        font-size: 16px;
        color: var(--el-text-color-primary);
        font-weight: 500;
      }

      p {
        margin: 0 0 8px 0;
        font-size: 14px;
        color: var(--el-text-color-regular);
      }

      .template-meta {
        display: flex;
        align-items: center;
        gap: 12px;

        .template-date {
          font-size: 12px;
          color: var(--el-text-color-placeholder);
        }
      }
    }

    .template-actions {
      display: flex;
      gap: 8px;
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .settings-view {
    padding: 12px;
  }

  .page-header .header-content {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }

  .template-item {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;

    .template-actions {
      justify-content: center;
    }
  }

  .setting-card .card-header {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }
}

// 全局样式覆盖
:deep(.template-preview-dialog) {
  .el-message-box__content {
    max-height: 400px;
    overflow-y: auto;
    white-space: pre-wrap;
    font-family: 'Courier New', monospace;
    font-size: 14px;
    line-height: 1.5;
  }
}

// 表单样式优化
:deep(.el-form-item) {
  margin-bottom: 24px;

  .el-form-item__label {
    font-weight: 500;
  }
}

:deep(.el-checkbox-group) {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

:deep(.el-radio-group) {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

// 暗色主题适配
@media (prefers-color-scheme: dark) {
  .template-item {
    &:hover {
      background-color: var(--el-color-primary-dark-2);
    }

    &.active {
      background-color: var(--el-color-primary-dark-2);
    }
  }
}
</style>
